package com.example.demo.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.example.demo.framework.CustomPage;
import com.example.demo.framework.base.BaseService;
import com.example.demo.model.Trade;

@Service
public class TradeService extends BaseService {

	@SuppressWarnings("unchecked")
	public CustomPage findTradeOrder(int pageNo, int pageSize, Trade trade, String username) {
		CustomPage cPage = new CustomPage();
		String field = " new Map(t.tID as tID, t.tradeID as tradeID, o.oID as oID, o.itemID as itemID, o.skuTitle as skuTitle , o.size as size, "
				+ "o.price*o.size as cPrice, t.discount as discount, t.discountPrice as discountPrice, t.postFee as postFee, "
				+ "t.payment as payment,t.receiverName as receiverName,l.express as express,l.logisticsNumber as logisticsNumber, "
				+ "t.status as status, t.createTime as createTime  ) ";
		StringBuilder hql = new StringBuilder(
				"SELECT %s FROM Order o LEFT JOIN Trade t ON t.tradeID=o.tradeID LEFT JOIN Logistics l on o.tradeID=l.tradeID LEFT JOIN UserInfo u on t.userID=u.userID WHERE 1=? ");
		List<Object> values = new ArrayList<>();
		values.add(1);
		if (trade.getUserID() != null) {
			hql.append(" and t.userID = ? ");
			values.add(trade.getUserID());
		}
		if (trade.getStatus() != null) {
			hql.append(" and t.status = ? ");
			values.add(trade.getStatus());
		}
		if (StringUtils.isNotEmpty(username)) {
			hql.append(" and u.username = ? ");
			values.add(username);
		}
		hql.append("order by t.tID desc");
		cPage.setContent(createQuery(String.format(hql.toString(), field), values.toArray())
				.setFirstResult(CustomPage.getStartOfPage(pageNo, pageSize)).setMaxResults(pageSize).getResultList());
		cPage.setTotal(
				(long) createQuery(String.format(hql.toString(), SQL_COUNT), values.toArray()).getSingleResult());
		cPage.setPageNo(pageNo+1);
		cPage.setSize(pageSize);
		return cPage;
	}

}
